package com.wangp.mywrite.coding;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @description: 单词替换
 * @author tooStronger
 * @date 2022/7/7
 */
public class ReplaceWord {

    public String replaceWords(List<String> dictionary, String sentence) {
        Set<String> set = new HashSet<>(dictionary);
        String[] sentences = sentence.split(" ");
        StringBuilder sb = new StringBuilder();
        for (String word : sentences) {
            int j = 0;
            for (j = 0; j < word.length(); j++) {
                String root = word.substring(0, j);
                if (set.contains(root)) {
                    sb.append(root).append(" ");
                    break;
                }
            }
            if (j == word.length()) {
                sb.append(word).append(" ");
            }
        }
        return sb.substring(0,sb.length()-1);
    }

    public static void main(String[] args) {
        System.out.println(new ReplaceWord().replaceWords(Arrays.asList("cat", "bat", "rat"), "the cattle was rattled by the battery"));
    }
}
